(function() {

    var $ = juliet.jQuery;

    /**
     * Field value helper
     */
    var FieldValueHelperClass = function() {

        this.fieldSelector = null;
        this.fieldValue = null;
        this.fieldValueModified = false;
        this.onFocusFieldValue = null;
        this.previousFieldValue = null;

        this.initialize = function(fieldSelector) {
            this.fieldSelector = fieldSelector;
            this.updateValue();
        };

        this.updateValue = function() {
            var newValue = [];

            $(this.fieldSelector).each(function() {
                var fieldType = this.type;

                if (fieldType == 'checkbox') {
                    newValue.push(this.checked);
                } else if (fieldType == 'radio') {
                    if (this.checked) newValue.push(this.value);
                } else {
                    newValue.push(this.value);
                }
            });

            this.fieldValue = ((newValue.length == 1) ? newValue[0] : newValue);
        };

        this.updatePreviousValue = function() {
            this.previousFieldValue = this.fieldValue;
        };

        this.updateOnFocusValue = function() {
            this.onFocusFieldValue = this.fieldValue;
        };

        this.isDifferentWithFocusValue = function() {
            return !this.isValuesEquals(this.onFocusFieldValue, this.fieldValue);
        };

        this.isDifferentWithPreviousValue = function() {
            return !this.isValuesEquals(this.previousFieldValue, this.fieldValue);
        };

        this.reset = function() {
            this.fieldValue = null;
            this.fieldValueModified = false;
            this.onFocusFieldValue = null;
            this.previousFieldValue = null;
        };

        this.isValuesEquals = function(value1, value2) {
            if ((value1 instanceof Array) && (value2 instanceof Array)) {
                return value1.toString() === value2.toString();
            }

            return (value1 === value2);
        };

    };

    juliet.registerModule('juliet.validation', 'FieldValueHelper-0.1', FieldValueHelperClass);

})();
